/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clip.net;

import L.L;
import clip.clipApp;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author admin
 */
public class HttpHandler implements com.sun.net.httpserver.HttpHandler {
    clipApp apptest;
//TODO wieder ändern in app
    public HttpHandler(clipApp app) {
        this.apptest = app;
    }

    private static String contentType(String fileName) {
        if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
            return "text/html";
        }
        return "";
    }

    public void handle(HttpExchange t) throws IOException {
        L.d("starte handling");
        InputStream is = t.getRequestBody();
        long bytesSent = 0;
        String token = getRequestString(t);
        //String filePath = app.options.downloadTokens.get(token);
        String filePath="d:\\heynow.mp3";
        if (filePath == null) {
            //TODO handle filepath not found
            return;
        }
        //Construct the response message.
        File file = new File(filePath);
        if (!file.exists()) {
            //TODO handle file doesnt exist
            return;
        }
        t.getResponseHeaders().add("content-disposition", "attachment; filename="+file.getName());
        //response headers
        t.sendResponseHeaders(200,file.length());
         //hier file senden
        OutputStream output = t.getResponseBody();
        try {
            //Send the entity body.
        FileInputStream fis = new FileInputStream(file);
            sendBytes(fis, output);
            fis.close();
            output.close();
        } catch (Exception ex) {
            Logger.getLogger(HttpHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String getRequestString(
            HttpExchange he) {
        return he.getRequestURI().toString().substring(1);
    }

    private long bytesSent = -1;
    private final int BUFFERSIZE=4096;
    private void sendBytes(FileInputStream fis, OutputStream os) throws Exception {
        byte[] buffer = new byte[BUFFERSIZE];
        int bytes = 0;
        while ((bytes = fis.read(buffer)) != -1) {
            os.write(buffer, 0, bytes);
            bytesSent += bytes;
            controlUploadSpeed();
        }
    }
    
    private long lastTimeChecked=0;
    private long lastTimeBytesSent=1;
    private int MAX_KB_PER_SECOND=0;
    private final int EXECUTIONTIME=5;
    private void controlUploadSpeed() {
//        if (lastTimeChecked==0) {
//            lastTimeChecked=System.currentTimeMillis();
//            return;
//        }
//        long timeElapsed=System.currentTimeMillis()-lastTimeChecked;
//        long bytesSent=getBytesSent()-lastTimeBytesSent;
//        long bytesPerSecond=Math.round(bytesSent/timeElapsed*(1000/timeElapsed));
//        long kiloBytesPerSecond=Math.round(bytesPerSecond/1024);
//        //hier jetzt so lang warten dass wieder passt
        // rausgenommen: kiloBytesPerSecond > MAX_KB_PER_SECOND &&
        if ( MAX_KB_PER_SECOND>0) {
            try {
                int waitTime=Math.round(1000/MAX_KB_PER_SECOND*1024/BUFFERSIZE)-EXECUTIONTIME;
                if (waitTime > 0) Thread.sleep(waitTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        lastTimeBytesSent=getBytesSent();
        lastTimeChecked=System.currentTimeMillis();
    }
    
    public long getBytesSent() {
        return bytesSent;
    }

}
